package com.zy.voteya;

import com.zy.voteya.entity.Items;
import com.zy.voteya.entity.Vote;
import com.zy.voteya.service.IItemsService;
import com.zy.voteya.service.IVoteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

@Component
public class DataInitializer implements CommandLineRunner {

    @Autowired
    private IVoteService voteService;

    @Autowired
    private IItemsService itemsService;

    @Override
    public void run(String... args) throws Exception {
        // 检查是否已有投票数据
        if (voteService.count() == 0) {
            System.out.println("开始初始化测试数据...");
            
            // 创建投票
            Vote vote = new Vote();
            vote.setVname("你最喜欢的编程语言");
            vote.setVtype("单选"); // 单选
            vote.setStartDate(LocalDate.now());
            vote.setEndDate(LocalDate.now().plusDays(7));
            voteService.save(vote);

            // 创建选项
            List<Items> itemsList = new ArrayList<>();
            Items item1 = new Items();
            item1.setIname("Java");
            item1.setVid(vote.getId());
            itemsList.add(item1);

            Items item2 = new Items();
            item2.setIname("Python");
            item2.setVid(vote.getId());
            itemsList.add(item2);

            Items item3 = new Items();
            item3.setIname("JavaScript");
            item3.setVid(vote.getId());
            itemsList.add(item3);

            Items item4 = new Items();
            item4.setIname("Go");
            item4.setVid(vote.getId());
            itemsList.add(item4);

            itemsService.saveBatch(itemsList);

            System.out.println("测试数据初始化完成！");
            System.out.println("创建的投票ID: " + vote.getId());
            System.out.println("请访问: http://localhost:8080/view.html?id=" + vote.getId() + " 查看投票结果");
        } else {
            System.out.println("数据库中已存在投票数据，跳过初始化。");
        }
    }
}